/*
 * 作者: junmu
 * 时间: 2025-07-22
 */
package com.hzbc.faceattendance.service.impl;

import com.hzbc.faceattendance.model.WhiteList;
import com.hzbc.faceattendance.repository.WhitelistRepository;
import com.hzbc.faceattendance.service.IWhitelistService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.Period;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

@Service
@Transactional
public class WhitelistServiceImpl implements IWhitelistService {

    @Autowired
    private WhitelistRepository whitelistRepository;

    public Page<WhiteList> getAllWhitelist(String keyword, Pageable pageable) {
        // 校验分页参数
        if (pageable.isUnpaged() || pageable.getPageSize() <= 0) {
            throw new IllegalArgumentException("分页参数无效");
        }

        if (pageable.getSort().isUnsorted()) {
            pageable = PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), Sort.by("createTime").ascending());
        }

        if (keyword != null && !keyword.isEmpty()) {
            return whitelistRepository.findByNameContaining(keyword, pageable);
        }
        return whitelistRepository.findAll(pageable);
    }

    public WhiteList addToWhitelist(WhiteList whitelist) {
        try {
            // 保存图片到服务器
            if (whitelist.getImageBase64() != null && !whitelist.getImageBase64().isEmpty()) {
                // 验证图片大小 (最大2MB)
                int maxSize = 2 * 1024 * 1024; // 2MB
                if (whitelist.getImageBase64().length() > maxSize * 4 / 3) { // Base64编码会增加约33%大小
                    throw new RuntimeException("图片大小不能超过2MB");
                }
                
                // 验证图片格式
                if (!whitelist.getImageBase64().startsWith("data:image/jpeg;base64,") && 
                    !whitelist.getImageBase64().startsWith("data:image/png;base64,")) {
                    throw new RuntimeException("只支持JPEG和PNG格式的图片");
                }
                
                // 提取纯Base64数据
                String base64Data = whitelist.getImageBase64().split(",")[1];
                byte[] imageBytes = Base64.getDecoder().decode(base64Data);
                
                // 验证实际图片数据
                if (imageBytes.length > maxSize) {
                    throw new RuntimeException("图片大小不能超过2MB");
                }
                
                String extension = whitelist.getImageBase64().startsWith("data:image/jpeg") ? "jpg" : "png";
                String fileName = UUID.randomUUID().toString() + "." + extension;
                Path path = Paths.get("uploads", fileName);
                Files.createDirectories(path.getParent());
                Files.write(path, imageBytes);
                whitelist.setImagePath(path.toString());
            }
            
            whitelist.setCreateTime(new Date());
            whitelist.setAge(Period.between(whitelist.getBirthDate(), LocalDate.now()).getYears());
            WhiteList saved = whitelistRepository.save(whitelist);
            // TODO: 调用海康设备API同步白名单
            return saved;
        } catch (IOException e) {
            throw new RuntimeException("图片保存失败", e);
        }
    }

    public WhiteList updateWhitelist(Long id, WhiteList whitelist) {
        whitelist.setId(id);
        whitelist.setUpdateTime(new Date());
        return whitelistRepository.save(whitelist);
    }

    public void deleteFromWhitelist(Long id) {
        WhiteList whitelist = whitelistRepository.findById(id).orElseThrow();
        whitelist.setIsDeleted(true);
        whitelistRepository.save(whitelist);
    }

    @Override
    public WhiteList findByName(String whiteName) {
        return whitelistRepository.findByNameContaining(whiteName);
    }

    @Override
    public WhiteList save(WhiteList whiteList) {
        return whitelistRepository.save(whiteList);
    }
}